// pages/envelopes/envelopes.js
const apiurl = require('../../config').apiurl;
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc();
Page({
  chengClone() {
    this.setData({
      envelopes: false
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    member_gradeid: 0, //获取会员等级id
    my_money: '', //我瓜分的红包
    timer: '',
    leftTime: 0, //红包倒计时
    countDown: '',
    envelopes: true,
    info: {},
    r_number: 0,
    goods: [],
    succenum: 0,
    sharePerson: false, //是否是分享人 true 是  false 否
    ro_id: '',
    // staffed:false, //红包被瓜分完
  },

  showWallet() {
    pulibc.navigateUrl('../cash/cash')
  },
  // 跳转到首页，让用户重新拆一个红包
  showRedEnvelopes() {
    // wx.reLaunch({
    //   url: '/pages/index/index',
    // })
    pulibc.navigateUrl('/pages/envelopes-get/envelopes-get')
  },
  // 分享帮用户拆红包
  bindOpenRed() {
    //isShare用来识别是来自分享还是正常领取的 isShare=0 正常领取 isShare=1分享领取  

    let url = apiurl + '/redenvelopes/openred'
    let ro_id = this.data.ro_id;
    let params = {};
    params.key = wx.getStorageSync('key');
    params.ro_id = ro_id;
    wx.request({
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      url: url,
      method: 'POST',
      data: params,
      success: data => {
        console.log("openred", data.data)
        if (data.data.code == 200) {
          // 刷新红包详情
          this.getOpenred(ro_id);
        } else if (data.data.code == 400) {
          // 已拆红包提示
          let errMsg = data.data.datas.error;
          if (errMsg == "已帮好友拆开红包") {
            pulibc.showToast('您已帮他拆过红包哦~', 'none');
          } else if (errMsg == "红包团员已满") {
            pulibc.showToast('红包团员已满，重新拆一个试试~', 'none');
          }
        } else if (data.data.datas.error == '请登录') {
          pulibc.navigateUrl('../register/register')
        }

      },
      fail: err => {}
    })
  },
  // 商品详情
  changeGoodsdetals(e) {
    console.log(e.currentTarget.dataset.goods_id)
    let id = e.currentTarget.dataset.goods_id
    pulibc.navigateUrl('../details-goods/details-goods?id=' + id)
  },
  // 获取会员接口
  getMemberInfo() {
    var keyVal = wx.getStorageSync('key');
    console.log(keyVal)
    wx.request({
      url: apiurl + '/member/index',
      data: {
        key: keyVal
      },
      success: data => {
        console.log(data.data.datas.member_info)
        if (data.data.code == 200) {
          var member_gradeid = data.data.datas.member_info.member_gradeid;
          // member_gradeid 0 非会员 1会员，2代理，3经销商，4众筹，5众筹+股份
          this.setData({
            member_gradeid
          })
        }
      }
    })
  },
  // 商品
  getGoods() {
    var type = 1;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: apiurl + '/goods/goods_list',
      data: {
        type: type
      },
      success: data => {
        if (data.data.code == 200) {
          console.log("goods", data);
          this.setData({
            goods: data.data.datas.goods,
          })
          wx.hideLoading();
        } else if (data.data.datas.error == '请登录') {
          pulibc.navigateUrl('../register/register')
        }
      }
    });
  },

  // 红包详情
  getOpenred(ro_id) {
    let url = apiurl + '/redenvelopes/redinfo'
    let params = {};
    params.key = wx.getStorageSync('key');
    params.ro_id = ro_id;
    // 分享领取时传入key，r_id,reo_id,type=2,正常领取传参：key,r_id,type=1
    console.log('redinfoparams', params)
    wx.request({
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      url: url,
      method: 'POST',
      data: params,
      success: data => {
        console.log("redinfo-data", data.data);
        if (data.data.code == 200) {
          let info = data.data.datas.info;
          // my_rend=true 是本人发起的，false则不是本人发起的
          let my_rend=info.my_rend;
          if(my_rend){
            this.setData({sharePerson:false});
          }else {
            this.setData({sharePerson:true});
          }

          console.log('my_rend', my_rend, 'sharePerson', this.data.sharePerson);
          let current_time = new Date().getTime();
          current_time = Math.floor(current_time / 1000);
          let leftTime = info.expiration_time - current_time;
          // let leftTime=1547975284-current_time;
 
          if (info.state == 1) {
            pulibc.showToast('您已成功瓜分红包!', 'none');
            // 当前用户拆分到的红包
            info.list.map(item => {
              if (item.member_id == info.t_member_id) {
                let my_money = item.money;
                this.setData({
                  my_money
                })
              }
            })
          }
          // 返回的state=0：领取中，state=1:领取成功，state=2：领取失败
          // state=1或state=2清除领取人标识（正确领取，分享领取）
          if (info.state == 1 || info.state == 2) {
            wx.removeStorageSync('ifShare');
          }
          this.setData({
            info,
            leftTime
          })
          console.log("leftTime", leftTime)
          let time = new Date(info.add_time * 1000);
          let date = time.toLocaleString(time);
          console.log('add_date', date)
          let e_time = new Date(info.expiration_time * 1000);
          let e_date = e_time.toLocaleString(e_time);
          console.log('e_date', e_date)
          this.countTime();
        }else if(data.data.code==400){
          // 红包失效，让用户重新领取
          if (data.data.datas.error == '很抱歉时间已经过期') {
            wx.showModal({
              title: '提示',
              content: '时间已过期，重新拆一个试试~~',
              showCancel: false,
              success: res => {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '/pages/envelopes-get/envelopes-get',
                  })
                }
              }
            })
          } else if (data.data.datas.error == '请登录') {
            pulibc.navigateUrl('../register/register')
          } 
          
        } 

      }
    })
  },
  // 红包倒计时
  countTime() {
    var that = this;
    let leftTime = parseInt(that.data.leftTime);
    that.setData({
      timer: setInterval(function() {
        var h, m, s;
        leftTime--;
        // console.log(leftTime)
        if (leftTime == 0) {
          console.log('已截止');
          clearInterval(that.data.timer);
          that.setData({
            countDown: '00:00:00'
          })
        }
        h = Math.floor(leftTime / 60 / 60 % 24);
        m = Math.floor(leftTime / 60 % 60);
        s = Math.floor(leftTime % 60);
        s = s < 10 ? "0" + s : s;
        m = m < 10 ? "0" + m : m;
        h = h < 10 ? "0" + h : h;
        that.setData({
          countDown: h + ':' + m + ':' + s
        })


      }, 1000)
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register?ro_id=" + options.ro_id
      })
    }
    let ro_id = options.ro_id;
    this.setData({
      ro_id
    })
    let ifShare = wx.getStorageSync('ifShare');
    this.getOpenred(ro_id);
    this.getMemberInfo();
    this.getGoods()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
   


  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var title = '赶紧邀请过来领取红包吧！'
    var ro_id = this.data.ro_id;
    var my_rend=this.data.info.my_rend;
    console.log(ro_id)
    return {
      title: title,
      path: '/pages/envelopes/envelopes?ro_id=' + ro_id
    }
  }
})